<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Python 中的并发主要涉及三种：多进程、多线程、协程。 相信提到多线程和多进程大家首先想到的是标准库 threading 和 multiprocessing。在 Python 中，这两个标准库几乎成了 Python 并发编程的代名词。对于这两个标准库，无论网络还是书籍，可查阅的资料非常丰富，我们不多做介绍。本文主要介绍从 Python3.2 开始被纳入标准库的 concurrent.futur">
<meta name="keywords" content="Python,并发">
<meta property="og:type" content="article">
<meta property="og:title" content="Python 并发编程之 future">
<meta property="og:url" content="https://l1xnan.gitee.io/posts/201807/39146.html">
<meta property="og:site_name" content="每天进步一点点">
<meta property="og:description" content="Python 中的并发主要涉及三种：多进程、多线程、协程。 相信提到多线程和多进程大家首先想到的是标准库 threading 和 multiprocessing。在 Python 中，这两个标准库几乎成了 Python 并发编程的代名词。对于这两个标准库，无论网络还是书籍，可查阅的资料非常丰富，我们不多做介绍。本文主要介绍从 Python3.2 开始被纳入标准库的 concurrent.futur">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-07-17T16:43:50.489Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python 并发编程之 future">
<meta name="twitter:description" content="Python 中的并发主要涉及三种：多进程、多线程、协程。 相信提到多线程和多进程大家首先想到的是标准库 threading 和 multiprocessing。在 Python 中，这两个标准库几乎成了 Python 并发编程的代名词。对于这两个标准库，无论网络还是书籍，可查阅的资料非常丰富，我们不多做介绍。本文主要介绍从 Python3.2 开始被纳入标准库的 concurrent.futur">






  <link rel="canonical" href="https://l1xnan.gitee.io/posts/201807/39146.html">



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Python 并发编程之 future | 每天进步一点点</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">每天进步一点点</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://l1xnan.gitee.io/posts/201807/39146.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="l1xnan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="每天进步一点点">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python 并发编程之 future
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-07-08 15:55:36" itemprop="dateCreated datePublished" datetime="2018-07-08T15:55:36+08:00">2018-07-08</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-07-18 00:43:50" itemprop="dateModified" datetime="2018-07-18T00:43:50+08:00">2018-07-18</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Python 中的并发主要涉及三种：多进程、多线程、协程。</p>
<p>相信提到多线程和多进程大家首先想到的是标准库 <code>threading</code> 和 <code>multiprocessing</code>。在 Python 中，这两个标准库几乎成了 Python 并发编程的代名词。对于这两个标准库，无论网络还是书籍，可查阅的资料非常丰富，我们不多做介绍。本文主要介绍从 Python3.2 开始被纳入标准库的 <code>concurrent.futures</code>，它是对 <code>threading</code> 和 <code>multiprocessing</code> 进一步的封装和高级别的抽象，并暴露出统一的接口，帮助开发者非常方便的实现异步调用。最初的提案见于 <a href="https://www.python.org/dev/peps/pep-3148/" target="_blank" rel="noopener">PEP 3148</a>。</p>
<a id="more"></a>

<h2 id="模块接口"><a href="#模块接口" class="headerlink" title="模块接口"></a>模块接口</h2><p><code>concurrent.futures</code> 模块提供的接口很简单，提供了类：</p>
<ul>
<li><code>Executor</code>：一个抽象类，提供异步执行调用的方法。 我们一般使用其具体的子类，而不直接调用它。</li>
<li><code>ThreadPoolExecutor</code>：是 <code>Executor</code> 的子类。提供了线程池的支持。</li>
<li><code>ProcessPoolExecutor</code>：是 <code>Executor</code> 的子类。提供了线程池的支持。把工作分配给多个 Python 进程处理。因此，如果需要做 CPU 密集型处理，使用这个模块能绕开 GIL，利用所有可用的 CPU 核心。</li>
<li><code>Future</code>：封装了可调用的异步执行。 其实例由 <code>Executor.submit()</code> 创建，表示可能已经完成或者尚未完成的延迟计算。</li>
</ul>
<p>以及模块函数：</p>
<ul>
<li><code>await(fs, timeout=None, return_when=ALL_COMPLETED)</code>：等待由 <code>fs</code> 给出的 <code>Future</code> 实例（可能由不同的 <code>Executor</code> 实例创建）完成。返回一个命名的 2 元组的集合。第一个集合，名为 <code>done</code>，包含在等待完成之前完成（完成或被取消）的 future。第二个集合，名为 <code>not_done</code>，包含未完成的 future。</li>
<li><code>as_completed(fs, timeout=None)</code>：返回由 <code>fs</code> 给出的 <code>Future</code> 实例（可能由不同的<code>Executor</code> 实例创建）的迭代器，它们在结束（结束状态可能是完成或被取消）时产生 future。 <code>fs</code> 复制的任何期货都将被退回一次。 在调用 <code>as_completed()</code>之前完成的任何 future 都将首先产生。 如果异步函数超时，则调用 <code>__next__()</code> 返回迭代器时会引发 <code>concurrent.futures.TimeoutError</code>。 <code>timeout</code> 可以是 <code>int</code> 或 <code>float</code>。如果未指定<code>timeout</code> 或 <code>None</code>，则等待时间没有限制。</li>
</ul>
<h3 id="Executor"><a href="#Executor" class="headerlink" title="Executor"></a>Executor</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">concurrent</span>.<span class="title">futures</span>.<span class="title">Executor</span></span></span><br></pre></td></tr></table></figure>

<p>它提供如下方法：</p>
<ul>
<li><code>submit(fn, *args, **kwargs)</code>：将可调用的 <code>fn</code> 调度为 <code>fn(* args ** kwargs)</code> 并返回表示可调用执行的 <code>Future</code> 对象。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> ThreadPoolExecutor(max_workers=<span class="number">1</span>) <span class="keyword">as</span> executor:</span><br><span class="line">    future = executor.submit(pow, <span class="number">323</span>, <span class="number">1235</span>)</span><br><span class="line">    print(future.result())</span><br></pre></td></tr></table></figure>

<ul>
<li><p><code>map(func, *iterables, timeout=None, chunksize=1)</code>：类似于 <code>map(func, *iterables)</code>，但是 <code>func</code> 是异步执行。若想并发运行多个可调用的对象可调用此函数。</p>
<ul>
<li><code>func</code>：需要异步执行的函数。</li>
<li><code>*iterables</code>：可迭代对象，如列表等。每一次 <code>func</code> 执行，都会从 <code>iterables</code> 中取参数。</li>
<li><code>timeout</code>：设置每次异步操作的超时时间。它的值可以是 <code>int</code> 或 <code>float</code>，如果操作超时，会返回 <code>raisesTimeoutError</code>；如果不指定 timeout 参数，则不设置超时间。</li>
</ul>
</li>
<li><p><code>shutdown(wait=True)</code>：向执行者发出信号，表示当目前待处理的期货执行完毕时，它应该释放它正在使用的任何资源。 在关闭后调用 <code>Executor.submit()</code> 和 <code>Executor.map()</code> 将引发 <code>RuntimeError</code>。</p>
</li>
</ul>
<p><code>ThreadPoolExecutor</code> 和 <code>ProcessPoolExecutor</code>，是 <code>Executor</code> 的子类，它们都实现了通用的 <code>Executor</code> 接口，因此使用 <code>concurrent.futures</code> 模块能特别轻松地把基于线程的方案转成基于进程的方案。</p>
<h3 id="ThreadPoolExecutor"><a href="#ThreadPoolExecutor" class="headerlink" title="ThreadPoolExecutor"></a>ThreadPoolExecutor</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ThreadPoolExecutor</span><span class="params">(max_workers=None, thread_name_prefix=<span class="string">''</span>)</span></span></span><br></pre></td></tr></table></figure>

<p>看官网中的<a href="https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor-example" target="_blank" rel="noopener">实例</a>，我们稍加改造：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> concurrent.futures <span class="keyword">as</span> futures</span><br><span class="line"><span class="keyword">import</span> urllib.request</span><br><span class="line"></span><br><span class="line">URLS = [<span class="string">'http://www.baidu.com/'</span>,</span><br><span class="line">        <span class="string">'http://www.qq.com/'</span>,</span><br><span class="line">        <span class="string">'http://www.sina.com.cn/'</span>,</span><br><span class="line">        <span class="string">'http://www.sohu.com/'</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># Retrieve a single page and report the URL and contents</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">load_url</span><span class="params">(url, timeout)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> urllib.request.urlopen(url, timeout=timeout) <span class="keyword">as</span> conn:</span><br><span class="line">        <span class="keyword">return</span> conn.read()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用 with 语句来确保及时清理线程</span></span><br><span class="line"><span class="keyword">with</span> futures.ThreadPoolExecutor(max_workers=<span class="number">5</span>) <span class="keyword">as</span> executor:</span><br><span class="line">    <span class="comment"># 开启加载每个 future，并用它们的 URL 来标记 future</span></span><br><span class="line">    future_to_url = &#123;executor.submit(load_url, url, <span class="number">60</span>): url <span class="keyword">for</span> url <span class="keyword">in</span> URLS&#125;</span><br><span class="line">    print(list(futures.as_completed(future_to_url)))</span><br><span class="line">    <span class="keyword">for</span> future <span class="keyword">in</span> futures.as_completed(future_to_url):</span><br><span class="line">        url = future_to_url[future]</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            data = future.result()</span><br><span class="line">        <span class="keyword">except</span> Exception <span class="keyword">as</span> exc:</span><br><span class="line">            print(<span class="string">'%r generated an exception: %s'</span> % (url, exc))</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            print(<span class="string">'%r page is %d bytes'</span> % (url, len(data)))</span><br></pre></td></tr></table></figure>

<h3 id="ProcessPoolExecutor"><a href="#ProcessPoolExecutor" class="headerlink" title="ProcessPoolExecutor"></a>ProcessPoolExecutor</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ProcessPoolExecutor</span><span class="params">(max_workers=None)</span></span></span><br></pre></td></tr></table></figure>

<p>其继承自 <code>Executor</code>，于其行为几乎一致。但是在 <code>map()</code> 方法中，使用 <code>ProcessPoolExecutor</code> 时，此方法将迭代器切换为多个块，并将其作为单独的任务提交到池中。 可以通过将 <code>chunksize</code> 设置为正整数来指定这些块的（近似）大小。 对于非常长的迭代，使用较大的 <code>chunksize</code> 值可以显着提高性能，而默认大小为 <code>1</code>。使用 <code>ThreadPoolExecutor</code> 时，<code>chunksize</code> 无效。</p>
<h3 id="Future"><a href="#Future" class="headerlink" title="Future"></a>Future</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Future</span></span></span><br></pre></td></tr></table></figure>

<p>它提供了如下方法（简单机翻一下￣ □ ￣｜｜）：</p>
<ul>
<li><p><code>cancel()</code><br>尝试取消调用。如果调用当前正在执行并且不能被取消，则该方法将返回 <code>False</code>，否则调用将被取消，并且该方法将返回 <code>True</code>。</p>
</li>
<li><p><code>cancelled()</code><br>如果调用成功取消，则返回 <code>True</code>。</p>
</li>
<li><p><code>running()</code><br>如果调用当前正在执行并且无法取消，则返回 <code>True</code>。</p>
</li>
<li><p><code>done()</code><br>如果调用成功取消或完成运行，则返回<code>True</code>。</p>
</li>
<li><p><code>result(timeout=None)</code><br>返回调用返回的值。如果调用尚未完成，则此方法将等待到 timeout 秒。如果调用在 <code>timeout</code> 秒内没有完成，则将产生 <code>concurrent.futures.TimeoutError</code>。 <code>timeout</code> 可以是 <code>int</code> 或 <code>float</code>。如果未指定 <code>timeout</code> 或 <code>None</code>，则等待时间没有限制。<br>如果 future 在完成之前被取消，则抛出 <code>CancelledError</code> 错误。<br>如果这个调用在执行过程中抛出异常，这种方法也将引发相同的异常。</p>
</li>
<li><p><code>exception(timeout=None)</code><br>返回调用引发的异常。如果调用尚未完成，则此方法将等待到 <code>timeout</code> 秒。如果调用在 <code>timeout</code> 秒内没有完成，则将产生 <code>concurrent.futures.TimeoutError</code>。 <code>timeout</code> 可以是 <code>int</code> 或 <code>float</code>。如果未指定 <code>timeout</code> 或 <code>None</code>，则等待时间没有限制。<br>如果未来在完成之前被取消，则 <code>CancelledError</code> 将被提出。<br>如果调用在未提高的情况下完成，则返回 <code>None</code>。</p>
</li>
<li><p><code>add_done_callback(fn)</code><br>将可调用 fn 附加到未来。 fn 将被调用，将来作为其唯一的参数，当未来被取消或完成运行时。<br>添加的 <code>callables</code> 按它们被添加的顺序被调用，并且总是在属于添加它们的进程的线程中被调用。如果可调用引发了 <code>Exception</code> 子类，它将被记录并被忽略。如果可调用引发了 <code>BaseException</code> 子类，则该行为是未定义的。<br>如果未来已经完成或被取消，<code>fn</code> 将立即被调用。</p>
</li>
</ul>
<h2 id="应用实例"><a href="#应用实例" class="headerlink" title="应用实例"></a>应用实例</h2><!--
```python
def download_many(cc_list):
    cc_list = cc_list[:5] ➊
    with futures.ThreadPoolExecutor(max_workers=3) as executor: ➋
        to_do = []
        for cc in sorted(cc_list): ➌
            future = executor.submit(download_one, cc) ➍
            to_do.append(future) ➎
            msg = 'Scheduled for {}: {}'
            print(msg.format(cc, future)) ➏
    results = []
    for future in futures.as_completed(to_do): ➐
        res = future.result() ➑
        msg = '{} result: {!r}'
        print(msg.format(future, res)) ➒
        results.append(res)
    return len(results)
``` -->

<p>综上，我们可以看到使用 <code>concurrent.future</code> 模块进行多线程、多进程编程会比用 <code>threading</code> 和 <code>multiprocessing</code> 简单许多。</p>
<p>参见：</p>
<ul>
<li><a href="http://www.dongwm.com/archives/%E4%BD%BF%E7%94%A8Python%E8%BF%9B%E8%A1%8C%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-PoolExecutor%E7%AF%87/" target="_blank" rel="noopener">使用 Python 进行并发编程-PoolExecutor 篇</a></li>
</ul>

      
    </div>

    

    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>l1xnan</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://l1xnan.gitee.io/posts/201807/39146.html" title="Python 并发编程之 future">https://l1xnan.gitee.io/posts/201807/39146.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/并发/" rel="tag"># 并发</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/201807/25528.html" rel="next" title="关于 JavaScript 闭包的简单例子">
                <i class="fa fa-chevron-left"></i> 关于 JavaScript 闭包的简单例子
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/201807/9553.html" rel="prev" title="Python 并发编程之 asyncio">
                Python 并发编程之 asyncio <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">l1xnan</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">43</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">14</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">39</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/l1xnan" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i></a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.yuque.com/l1xnan" target="_blank" title="语雀"><i class="fa fa-fw fa-crow"></i></a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#模块接口"><span class="nav-number">1.</span> <span class="nav-text">模块接口</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Executor"><span class="nav-number">1.1.</span> <span class="nav-text">Executor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ThreadPoolExecutor"><span class="nav-number">1.2.</span> <span class="nav-text">ThreadPoolExecutor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ProcessPoolExecutor"><span class="nav-number">1.3.</span> <span class="nav-text">ProcessPoolExecutor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Future"><span class="nav-number">1.4.</span> <span class="nav-text">Future</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#应用实例"><span class="nav-number">2.</span> <span class="nav-text">应用实例</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">l1xnan</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.9.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a> v6.3.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  



	





  





  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  

  


  
  

  

  

  

  

  

</body>
</html>
